package cn.wp.ewallet.wallet.service.impl;

import cn.wp.common.core.dao.JdbcSupportTemplate;
import cn.wp.common.core.dao.annotation.Table;
import cn.wp.common.core.model.WpPage;
import cn.wp.ewallet.wallet.service.BaseService;
import com.mysql.jdbc.StringUtils;

import java.io.Serializable;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

public class BaseServiceImpl<T> implements BaseService<T> {

    private JdbcSupportTemplate jdbcSupportTemplate;

    private String tableName;

    private String key;

    private Class aClass;

    {
        //获得带有泛型的父类
        Type genericSuperclass =this.getClass().getGenericSuperclass();
        //判断父类是不是参数化的类型，如果是强转成ParameterizedType
        if (genericSuperclass instanceof ParameterizedType) {
            ParameterizedType parameterizedType = (ParameterizedType) genericSuperclass;
            //获得Demo1<String>，<>中的实际类型参数
            Type[] actualTypeArguments = parameterizedType.getActualTypeArguments();
            //获得参数类型
            Class<?> clazz = (Class<?>) actualTypeArguments[0];
            aClass = clazz;
            Table annotation = clazz.getAnnotation(Table.class);
            if (annotation != null) {
                tableName = annotation.value();
                key = annotation.keys()[0];
            }
        }

    }

    public BaseServiceImpl(JdbcSupportTemplate jdbcSupportTemplate) {
        this.jdbcSupportTemplate = jdbcSupportTemplate;
    }

    @Override
    public void updateByPrimaryKey(T... t) {
        int i = 1 / t.length;
        Arrays.stream(t).forEach(entity->jdbcSupportTemplate.innerUpdate(entity,aClass,tableName));
    }

    @Override
    public void insert(T... t) {
        int i = 1 / t.length;
        for (T t1 : t) {
            jdbcSupportTemplate.insert(t1,tableName,aClass);
        }
    }

    @Override
    public int[] delete(Serializable... ids) {
        int i = 1 / ids.length;
        return jdbcSupportTemplate.deleteByIds(Arrays.stream(ids).collect(Collectors.toList()),aClass);
    }

    @Override
    public List<T> select(String where) {
        StringBuilder sb = new StringBuilder("select * from " + tableName);

        if (!StringUtils.isNullOrEmpty(where)){
            sb.append(" where ");
            sb.append(where);
        }
        return jdbcSupportTemplate.selectList(sb.toString(), null, aClass);
    }

    @Override
    public <E> WpPage<E> selectList(String sql, Object[] params, WpPage page, Class<E> clazz) {
        return jdbcSupportTemplate.selectList(sql,params,page,clazz);
    }

    @Override
    public void execute(String sql){
        jdbcSupportTemplate.execute(sql,null);
    }
}
